export default {
	props: {
		value: { type: Boolean, default: false },
		child: { type: Boolean, default: false },
		dataId: { type: String, default: '' }
	},
	data() {
		return {
			visible: this.value,
			formData: {},
			loading: false,
			btnLoading: false,
			formConfig: {
				ref: 'form',
				size: 'medium',
				class: 'dialog_form_wrapper'
			}
		}
	},
	computed: {
		addOrEdit() {
			return !this.dataId;
		},
		formTypeName() {
			return !this.addOrEdit && !this.child ? '修改' : '新增';
		},
		dialogTitle() {
			let isChildData = !this.child ? '' : '子';
			return `${this.formTypeName}${isChildData}${this.formName}`;
		}
	},
	watch: {
		value(flag) {
			this.visible = flag;
		},
		async visible(flag) {
			this.$emit('input', flag);
			if (!flag) {
				this.$emit('update:child', false);
				return false;
			}
			await this.initializeFormData();
			if (!!this.formatFormParams) {
				this.formatFormParams(this.formData);
			}
		}
	},
	methods: {
		//初始化表单数据
		async initializeFormData() {
			this.loading = true;
			this.formData = {};
			if (this.addOrEdit) {
				this.$nextTick(() => {
					this.$refs['form'].resetFields();
					this.loading = false;
					this.formData = {};
				})
			} else if (this.child) {
				this.$nextTick(() => {
					this.$refs['form'].resetFields();
					this.formData = {
						pid: this.dataId,
					};
					this.loading = false;
				})
			} else {
				let datas = await this.getDetailData();
				this.$refs['form'].resetFields();
				this.formData = { ...datas };
				this.loading = false;
			}
		},

		//获取详情数据
		async getDetailData() {
			let params = !this.requestParams ? this.dataId : this.requestParams;
			let result = await this.detailData(params).then((res) => res.data);
			if (result.code === '0') {
				return this.$detailData(result.data);
			}
		},

		//提交表单
		handleSubmitForm() {
			this.$refs['form'].validate(async (valid) => {
				if (!valid) return false;
				this.btnLoading = true;
				if (!this.beforeSubmitForm) {
					await this.submitFormRequest();
				} else {
					await this.beforeSubmitForm();
					await this.submitFormRequest();
				}
				this.btnLoading = false;
			});
		},

		//格式化请求参数
		async formatRequestParams() {
			if (!this.submitParams) {
				return Promise.resolve(this.formData);
			} else {
				return Promise.resolve(this.submitParams);
			}
		},

		//提交表单请求
		async submitFormRequest() {
			let params = await this.formatRequestParams();
			let result = await this.callFunction(params).then(res => res.data);
			if (result.code === '0') {
				this.visible = false;
				this.$emit('refresh');
				this.updateStoreData?.();
				this.$message.success(`${this.dialogTitle}成功`);
			}
		}
	}
}